<?php
/**
 * Created by PhpStorm.
 * User: 七月
 * Date: 2017/2/12
 * Time: 19:44
 */

namespace app\lib\exception;

use think\exception\Handle;

use think\Log;
use think\Request;
use Exception;

/*
 * 重写Handle的render方法，实现自定义异常消息
 */
class ExceptionHandler extends Handle
{
    private $code;
    private $msg;
    private $errorCode;

    public function render(Exception $e){

        if ($e instanceof BaseException)
        {
            $this->errorCode = $e->error_code;
            $this->code = $e->code;
            $this->msg = $e->msg;

        }
        else{
            // 如果是服务器未处理的异常，将http状态码设置为500，并记录日志
            if(config('app_debug')){
                // 调试状态下需要显示TP默认的异常页面，因为TP的默认页面
                // 很容易看出问题

                return parent::render($e);
            }

            $this->code = 500;
            $this->msg = 'sorry，we make a mistake. (^o^)Y';
            $this->errorCode = 999;
            $this->recordErrorLog($e);
        }


        $result = [
            'error_code' => $this->errorCode,
            'msg'  => $this->msg,
            'request_url' => $request = \think\facade\Request::url()
        ];

        return json($result, $this->code);
    }

    /*
     * 将异常写入日志
     */
    private function recordErrorLog(Exception $e)
    {

        \think\facade\Log::init([
            'type'  =>  'File',
            'path'  =>  EXCEPTION_LOG_PATH,
            'level' => ['error'],
            'max_files'   => 30,
            'json'	=>	true,
        ]);

        //        Log::record($e->getTraceAsString());
        \think\facade\Log::write($e->getMessage(),'error');
    }
}